/**
 * 
 */
package com.feib.stms.security.web.authentication;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;

import com.feib.stms.model.User;
import com.feib.stms.model.UserLoginControl;
import com.feib.stms.security.core.userdetails.StmsUserDetailsWrapper;
import com.feib.stms.service.UserLoginControlService;


/**
 * 使用者登入需做的其他檢核<br />
 * <li>密碼過期檢核</li>
 * <li>使用者已登入檢核</li>
 * @author Jimmy Liu
 *
 */
public class StmsPostAuthenticationChecks implements UserDetailsChecker {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    private UserLoginControlService userLoginControlService;
    
	public void check(UserDetails user) 
	{
		logger.debug("檢核使用者("+user.getUsername()+")密碼是否過期");
		// 檢核密碼是否過期
		if (!user.isCredentialsNonExpired()) {
            logger.debug("User account credentials have expired");

            throw new CredentialsExpiredException("User credentials have expired", user);
        }

		logger.debug("檢核使用者("+user.getUsername()+")是否重複登入");
		// 檢核使用者是否是否重複登入
		if (user instanceof StmsUserDetailsWrapper )
		{
			User dbUser = ((StmsUserDetailsWrapper) user).getUser();
			UserLoginControl userLoginControl = userLoginControlService.findByUerIdGroupNo(dbUser);
			if (null == userLoginControl)
			{
				userLoginControl = new UserLoginControl();
	            userLoginControl.setActived(Boolean.TRUE);
	            userLoginControl.setUser(dbUser);
				dbUser.setUserLoginControl(userLoginControl);
			}
			else
			{
				dbUser.setUserLoginControl(userLoginControl);
				if (Boolean.TRUE.equals(userLoginControl.getActived()))
				{
		            throw new UserIsActivedAuthenticationException("User have logon", user);
				}
			}
		}
	}

	/**
	 * @param userLoginControlService 的設定的 userLoginControlService
	 */
	public void setUserLoginControlService(
			UserLoginControlService userLoginControlService) {
		this.userLoginControlService = userLoginControlService;
	}

}
